<?php
/**
 +---------------------------------------------------------- 
 * date: 2018-05-03 11:08:42
 +---------------------------------------------------------- 
 * author: Raoxiaoya
 +---------------------------------------------------------- 
 * describe: 用户金币数回写到数据库
 +---------------------------------------------------------- 
 */

use \Logic\Factory;
use \Lib\Config;
use Logic\Model\PlayerInfoModel;
use Logic\Model\PlayerModel;

set_time_limit(0);
require('Lib/Common.php');

class Player
{
	private $redis;
	private $mod;
	private $logs;
	private $tag = 'user_info';
	private $game = 'user_status';
	private $logTag = 'player_info';
	private $time_limit = 604800; // 一周

	public function __construct(){
		$this->mod    	= Config::$mod;
		$this->logs    	= Factory::getLogger();
	}

	public function main(){

		while(true)
		{
			$this->write();
			sleep(5);
		}

	}

	protected function write(){
		$start = time();
		for($i = 0; $i < $this->mod; $i++){
			$this->redis = Factory::getPlayerRedis($i);
			$prefix =  $this->tag . ':*';
			$players = $this->redis->handler->keys($prefix);
			while(count($players))
			{
				$key = array_pop($players);
				// 需回写的字段
				$fields1 = [
					'player_header_image',
					'player_nickname',
				];
				$fields2 = [
					'player_coins',
					'player_login_time',
					'player_login_ip',
				];
				$result = $this->redis->handler->hMget($key, array_merge($fields1,$fields2));
				$array = explode(':', $key);

				$info = PlayerInfoModel::getInstance()->where('player_id', $array[2])->getOne();

				if(!$info){
					$this->redis->handler->delete($key);
					$this->logs->error($this->logTag,'玩家' . $array[2] . '不存在');
				}else{
					if(!empty($fields1)){
						$up1 = [];
						foreach($fields1 as $v1){
							$up1[$v1] = $result[$v1];
						}

						PlayerModel::getInstance()->where('player_id', $array[2])->update($up1);
					}

					if(!empty($fields2)){
						$up2 = [];
						foreach($fields2 as $v2){
							$up2[$v2] = $result[$v2];
						}
						PlayerInfoModel::getInstance()->where('player_id', $array[2])->update($up2);
					}

					if((time() - $result['player_login_time']) > $this->time_limit){
						// 判断是否在游戏里
						$key_game = str_replace($this->tag, $this->game, $key);
						if(!$this->redis->handler->exists($key_game)){
							$this->redis->handler->delete($key);
						}
					}
				}
			}

			$this->redis->deinitDataRedis();
		}

		$end = time();
		$this->logs->info($this->logTag,'耗时: ' . ($end - $start) . ' seconds');
	}
}


// 玩家信息回写到数据库
$obj = new Player();
$obj->main();
